/**
 * Copyright (C), 2020, 安徽贝慕信息科技有限公司
 * FileName: IpCheckFilter
 * Author:   Allen
 * Date:     2020/08/21 10:04
 * Description: 网关的白名单过滤
 * History:
 * <author>          <time>          <version>          <desc>
 * 作者姓名           修改时间           版本号              描述
 */
package com.bim.marvel.gateway.filter;

import com.alibaba.fastjson.JSONObject;
import com.bim.marvel.gateway.config.IpCheckListConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.net.InetAddress;
import java.nio.charset.StandardCharsets;

/**
 * 〈网关的Ip名单过滤〉
 *
 * @author Allen
 * @date 2020/08/21
 * @since 1.0.0
 */
@Component
@Slf4j
public class IpCheckFilter implements GlobalFilter {

    /**
     * IP限制的配置类
     */
    @Autowired
    private IpCheckListConfig ipConfig;

    /**
     * 网关全局过滤
     * @param exchange 请求上下文
     * @param chain 网关过滤链
     * @return Void
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        InetAddress address = exchange.getRequest().getRemoteAddress().getAddress();
        String hostName = address.getHostName();
        if (!CollectionUtils.isEmpty(ipConfig.getBlackList()) && ipConfig.getBlackList().contains(hostName)) {
            return responseIpNoInvalid(exchange);
        }
        if (!CollectionUtils.isEmpty(ipConfig.getWhiteList()) && !ipConfig.getWhiteList().contains(hostName)) {
            return responseIpNoInvalid(exchange);
        }
        return chain.filter(exchange);
    }

    /**
     * 响应请求禁止
     * @param exchange 请求上下文
     * @return Void
     */
    private Mono<Void> responseIpNoInvalid(ServerWebExchange exchange) {
        ServerHttpResponse response = exchange.getResponse();
        JSONObject data = new JSONObject();
        data.put("code", HttpStatus.FORBIDDEN);
        data.put("message", "非法请求!");
        byte[] datas = data.toJSONString().getBytes(StandardCharsets.UTF_8);
        DataBuffer buffer = response.bufferFactory().wrap(datas);
        response.setStatusCode(HttpStatus.FORBIDDEN);
        response.getHeaders().add("Content-Type", MediaType.APPLICATION_JSON_UTF8_VALUE);
        return response.writeWith(Mono.just(buffer));
    }
}
